﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace 软构作业Winform
{
    public partial class Form3 : Form
    {
        private HttpClient client;

        public Form3()
        {
            InitializeComponent();
            client = new HttpClient();
        }

        private void Form3_Load(object sender, EventArgs e)
        {

        }

        private async void button1_Click(object sender, EventArgs e)
        {
            string url = URL_text.Text.Trim();
            if (string.IsNullOrEmpty(url))
            {
                MessageBox.Show("输入为空，请输入URL地址！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }
            try
            {
                // 获取网页内容
                string html = await client.GetStringAsync(url);
                // 正则表达式匹配电话号码  (?:^|\D)(1[3-9]\d)([-]?)(\d{4})([-]?)(\d{4})(?:^|\D)
                MatchCollection phoneMatches = Regex.Matches(html, @"(?:^|\D)(1[3-9]\d[- ]?\d{4}[- ]?\d{4})(?:$|\D)");
                List<string> phones = new List<string>();
                foreach (Match m in phoneMatches)
                {
                    string num = m.Groups[1].Value + m.Groups[3].Value + m.Groups[5].Value;
                    phones.Add(num);
                }

                // 正则表达式匹配邮箱 
                MatchCollection emailMatches = Regex.Matches(html, @"\b[a-zA-Z0-9._%+-]+@[a-zA-Z0-9,-]+(\.[a-zA-Z]{2,})+\b");
                List<string> emails = new List<string>();
                foreach (Match m in emailMatches)
                {
                    emails.Add(m.Value);
                }

                // 展示电话号码和邮箱
                phones_list.DataSource = phones;
                emails_list.DataSource = emails;
            }
            catch (UriFormatException)
            {
                MessageBox.Show("URL格式不正确。", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            catch(HttpRequestException ex)
            {
                MessageBox.Show($"访问网页出错：{ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            catch(Exception ex)
            {
                MessageBox.Show($"发生错误：{ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
    }
}
